package com.hxkj.controller;

import com.hxkj.domain.po.Token;
import com.hxkj.token.TokenGenerator;
import com.hxkj.domain.po.LoginToken;
import com.platform.common.domain.result.ResultDataStruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.Callable;

/**
 * created by kezhijie on 2018/8/22 11:11.
 * email to kezhijie@hxoss.com
 */
@RestController
@RequestMapping("/token")
public class TokenController {

    @Autowired
    private TokenGenerator tokenGenerator;

    @GetMapping(value = "/refresh")
    public Callable<ResultDataStruct<LoginToken>> refresh(@RequestParam("token") String token) throws Exception {
        return () -> {
            ResultDataStruct<LoginToken> resultDataStruct = new ResultDataStruct<>();
            try {
                LoginToken loginToken = tokenGenerator.refreshToken(token);

                resultDataStruct.setCode(200);
                resultDataStruct.setMessage("成功");
                resultDataStruct.setData(loginToken);
            } catch (Exception e) {
                resultDataStruct.setCode(500);
                resultDataStruct.setMessage(e.getMessage());
            }
            return resultDataStruct;
        };
    }

    @PostMapping(value = "validate")
    public Callable<ResultDataStruct<Token>> validate(@RequestBody String accessToken) {
        return () -> {
          ResultDataStruct<Token> resultDataStruct = new ResultDataStruct<>();

          try {
              Token token = tokenGenerator.validateToken(accessToken);
              resultDataStruct.setCode(200);
              resultDataStruct.setMessage("成功");
              resultDataStruct.setData(token);
          } catch (Exception e) {
              resultDataStruct.setCode(500);
              resultDataStruct.setMessage(e.getMessage());
          }
          return resultDataStruct;
        };
    }
}
